package cn.mdmbct.spring.starter.douyin.life.config;

import cn.mdmbct.douyin.common.config.HttpConfig;
import cn.mdmbct.douyin.common.http.apache.ApacheHttpExecutorFactory;
import cn.mdmbct.douyin.common.http.okhttp.OkHttpExecutorFactory;
import cn.mdmbct.douyin.common.storage.DyStorageManager;
import cn.mdmbct.douyin.life.service.DyLifeServiceImpl;
import cn.mdmbct.douyin.life.service.interfaces.DyLifeService;
import cn.mdmbct.spring.starter.douyin.common.properties.dy.DyOpenApiProperties;
import cn.mdmbct.spring.starter.douyin.common.properties.dy.HttpProperties;
import org.springframework.beans.BeanUtils;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author mdmbct  mdmbct@outlook.com
 * @date 2021/3/19 22:26
 * @modified mdmbct
 * @since 1.0
 */
@Configuration
public class DyOpenApiLifeServiceAutoConfiguration {

    @Bean
    @ConditionalOnMissingBean
    public DyLifeService dyLifeService(DyOpenApiProperties apiProperties, DyStorageManager storageManager) {

        HttpProperties httpProperties = apiProperties.getHttp();
        HttpConfig httpConfig = new HttpConfig();
        BeanUtils.copyProperties(httpProperties, httpConfig);
        switch (httpProperties.getType()) {
            case OK_HTTP:
                return getDyLifeServiceWithOkHttp(httpConfig, storageManager);
            case APACHE_HTTP:
                return getDyLifeServiceWithApacheHttp(httpConfig, storageManager);
            default:
                return getDefaultDyLifeServiceImpl(httpConfig, storageManager);
        }
    }


    private DyLifeService getDyLifeServiceWithOkHttp(HttpConfig httpConfig, DyStorageManager storageManager) {

        return new DyLifeServiceImpl(storageManager, new OkHttpExecutorFactory().createHttpExecutor(httpConfig));
    }

    private DyLifeService getDyLifeServiceWithApacheHttp(HttpConfig httpConfig, DyStorageManager storageManager) {
        return new DyLifeServiceImpl(storageManager, new ApacheHttpExecutorFactory().createHttpExecutor(httpConfig));
    }

    private DyLifeService getDefaultDyLifeServiceImpl(HttpConfig httpConfig, DyStorageManager storageManager) {
        return getDyLifeServiceWithOkHttp(httpConfig, storageManager);
    }
}
